package top.roadvast.rabbitmq.consumer;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import org.springframework.boot.test.context.SpringBootTest;
import top.roadvast.rabbitmq.utils.RabbitmqUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeoutException;

/**
 * @Author 郭泽鹏
 * @Date 2021/12/27 8:58
 * @Version 1.0
 * @Description rabbitmq六种工作模式之一：扇出模式
 * 将日志存储到磁盘
 */
@SpringBootTest
public class FanoutConsumer02 {
    public static void main(String[] args) {
        final Connection connection = RabbitmqUtil.getConnection();
        try {
            Channel channel = connection.createChannel();
            //参数：交换机名称，交换机类型
            channel.exchangeDeclare("logs", "fanout");
            //非持久,独占,自动删除
            final String queueName = channel.queueDeclare().getQueue();
            //把该队列,绑定到 logs 交换机
            //对于 fanout 类型的交换机, routingKey会被忽略，不允许null值
            channel.queueBind(queueName, "logs", "");
            DeliverCallback deliverCallback = (consumerTag, message) -> {
                String msg = new String(message.getBody(), StandardCharsets.UTF_8);
                LocalDate localDate = LocalDate.now();
                String format = localDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
                System.out.println("日志写入到：[" + System.getProperty("user.dir") + "/logs/" + format + ".log]文件中。");
                File file = new File(System.getProperty("user.dir") + "/logs/" + format + ".log");
                try(final FileOutputStream outputStream = new FileOutputStream(file, true);) {      //第二个操作：追加文件，默认为false
                    outputStream.write(msg.getBytes());
                    outputStream.write("\n".getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            };
            CancelCallback cancelCallback = (consumerTag) -> {

            };
            channel.basicConsume(queueName, true, deliverCallback, cancelCallback);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
